package cn.sylinx.horm.dialect.type;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.ServiceLoader;

import cn.sylinx.horm.dialect.DbType;
import cn.sylinx.horm.type.TypeHandlerRegistry;
import cn.sylinx.horm.util.ClassUtil;

public class TypeHandlerBuilderFactory {

    private static final TypeHandlerBuilderFactory instance = new TypeHandlerBuilderFactory();

    private final Map<DbType, TypeHandlerBuilder> registers = new HashMap<DbType, TypeHandlerBuilder>();

    private final TypeHandlerBuilder defaultTypeHandlerBuilder = TypeHandlerRegistry.DEFAULT_INSTANCE;

    public static TypeHandlerBuilderFactory get() {
        return instance;
    }

    private TypeHandlerBuilderFactory() {
        registerDefault();
        loadFromService();
    }

    /**
     * 注册 TypeHandlerBuilder
     */
    private void registerDefault() {
    }

    private final void loadFromService() {
        ServiceLoader<TypeHandlerBuilderProvider> thbSpi = ServiceLoader.load(TypeHandlerBuilderProvider.class,
                ClassUtil.getDefaultClassLoader());
        if (thbSpi != null) {
            Iterator<TypeHandlerBuilderProvider> thbIt = thbSpi.iterator();
            while (thbIt != null && thbIt.hasNext()) {
                Map<DbType, TypeHandlerBuilder> thbMaps = thbIt.next().create();
                if (thbMaps != null) {
                    registers.putAll(thbMaps);
                }
            }
        }
    }

    public TypeHandlerBuilder getTypeHandlerBuilder(DbType dbType) {
        TypeHandlerBuilder thb = registers.get(dbType);
        if (thb == null) {
            return defaultTypeHandlerBuilder;
        }
        return thb;
    }
}
